package com.lxs.mall.service.Impl;

import com.lxs.mall.common.Constant;
import com.lxs.mall.exception.LxsMallException;
import com.lxs.mall.exception.LxsMallExceptionEnum;
import com.lxs.mall.service.UploadService;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 小松
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${file.upload.uri}")
    String uri;

    @Override
    public void createImage(File fileDirectory, MultipartFile file, File destFile) {
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new LxsMallException(LxsMallExceptionEnum.MKDIR_FAILED);
            }
        }
        try {
            //把原本的文件传送到destFile定义的文件夹
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String newFileName = getNewFileName(file);
        //创建文件
        //File里面可以直接放路径，但是最好使用这种方法方便后续进行完善修改
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        createImage(fileDirectory, file, destFile);
        String address = uri;
        return "http://" + address + "/images/" + newFileName;
    }

    @Override
    public String getNewFileName(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件文件名称UUID
        UUID uuid = UUID.randomUUID();
        //文件名在.后缀
        return uuid + suffixName;
    }

    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        String newFileName = getNewFileName(file);
        //创建文件
        //File里面可以直接放路径，但是最好使用这种方法方便后续进行完善修改
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        createImage(fileDirectory, file, destFile);

        /**
         * watermark(图片上打水印的位置,水印图片的具体位置,透明度)
         */
        Thumbnails.of(destFile).size(Constant.IMAGE_SIZE, Constant.IMAGE_SIZE)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(
                        new File(Constant.FILE_UPLOAD_DIR
                                + Constant.WATER_MARK_JPG)), Constant.IMAGE_OPACITY)
                .toFile(new File(Constant.FILE_UPLOAD_DIR + newFileName));

        String address = uri;
        return "http://" + address + "/images/" + newFileName;
    }
}
